package com.twotiger.and.activity.base;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;
import app.twotiger.p2p.R;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.readystatesoftware.systembartint.SystemBarTintManager.SystemBarConfig;
import com.twotiger.and.Constants;
import com.twotiger.and.TwoTigerApp;
import com.twotiger.and.activity.user.LockActivity;
import com.twotiger.and.bean.BanklistItem;
import com.twotiger.and.bean.Basebean;
import com.twotiger.and.bean.ConstantData;
import com.twotiger.and.bean.ConstantDataUnit;
import com.twotiger.and.util.HttpUtil;
import com.twotiger.and.util.ListUtils;
import com.twotiger.and.util.LogUtil;
import com.twotiger.and.util.NetWorkUtil;
import com.twotiger.and.util.PackageUtils;
import com.twotiger.and.util.PreferencesUtils;
import com.twotiger.and.util.PromptManager;
import com.twotiger.and.util.RandomUtils;
import com.twotiger.and.util.Signature;
import com.twotiger.and.util.StringUtils;
import com.umeng.analytics.MobclickAgent;

public abstract class BaseActivity extends FragmentActivity implements OnClickListener {
    protected Context mContext;
    private static Activity mactivity;

    private HashMap<String, String> parms;
    public TwoTigerApp application;
    private LayoutInflater inflater;
    public SystemBarTintManager tintManager;

    public static String CONSTANTDATA = "constantdata";

    public boolean getRegistTag() {
        return application.isRegistSuccess();
    }

    /**handler继承base 方便统一处理系统类消息*/
    protected BaseHandler handler;
    /**允许手势拦截*/
    protected boolean gestureEnable = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        mContext = this;
        parms = new HashMap<String, String>();
        handler = new BaseHandler(this);
        application = TwoTigerApp.getInstance();
        application.addActivity(this);
        inflater = LayoutInflater.from(mContext);
        View view = loadViewLayout(inflater);
        setContentView(view);
        // 4.4 festure
        // create our manager instance after the content view is set
        tintManager = new SystemBarTintManager(this);
        // enable status bar tint
        tintManager.setStatusBarTintEnabled(true);
        // enable navigation bar tint
        tintManager.setNavigationBarTintEnabled(true);
        // set a custom tint color for all system bars
        SystemBarConfig config = tintManager.getConfig();
        view.setPadding(0, config.getPixelInsetTop(false), 0, config.getPixelInsetBottom());
        //设置状态栏颜色
        tintManager.setTintResource(R.drawable.bg_common_statusbar);
        findViewById(view);
        setListener();
        processLogic();

    }

    /**
     * 是否允许手势密码拦击展示 
     * @param gestureEnable
     */
    protected void setGestureEnable(boolean gestureEnable) {
        this.gestureEnable = gestureEnable;
    }

    public void setStatusBarBlack(Window window, boolean dark) {
        FlymeSetStatusBarLightMode(window, dark);
        MIUISetStatusBarLightMode(window, dark);
    }

    /**
     * 设置状态栏图标为深色和魅族特定的文字风格
     * 可以用来判断是否为Flyme用户
     * @param window 需要设置的窗口
     * @param dark 是否把状态栏字体及图标颜色设置为深色
     * @return  boolean 成功执行返回true
     *
     */
    public boolean FlymeSetStatusBarLightMode(Window window, boolean dark) {
        boolean result = false;
        if (window != null) {
            try {
                WindowManager.LayoutParams lp = window.getAttributes();
                Field darkFlag = WindowManager.LayoutParams.class
                    .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
                Field meizuFlags = WindowManager.LayoutParams.class.getDeclaredField("meizuFlags");
                darkFlag.setAccessible(true);
                meizuFlags.setAccessible(true);
                int bit = darkFlag.getInt(null);
                int value = meizuFlags.getInt(lp);
                if (dark) {
                    value |= bit;
                } else {
                    value &= ~bit;
                }
                meizuFlags.setInt(lp, value);
                window.setAttributes(lp);
                result = true;
            } catch (Exception e) {

            }
        }
        return result;
    }

    /**
     * 控制应用的字号不受系统字号大小设置的影响
     * @see android.view.ContextThemeWrapper#getResources()
     */
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    /**
     * 设置状态栏字体图标为深色，需要MIUIV6以上
     * @param window 需要设置的窗口
     * @param dark 是否把状态栏字体及图标颜色设置为深色
     * @return  boolean 成功执行返回true
     *
     */
    public boolean MIUISetStatusBarLightMode(Window window, boolean dark) {
        boolean result = false;
        if (window != null) {
            Class clazz = window.getClass();
            try {
                int darkModeFlag = 0;
                Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
                Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
                darkModeFlag = field.getInt(layoutParams);
                Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
                if (dark) {
                    extraFlagField.invoke(window, darkModeFlag, darkModeFlag);//状态栏透明且黑色字体
                } else {
                    extraFlagField.invoke(window, 0, darkModeFlag);//清除黑色字体
                }
                result = true;
            } catch (Exception e) {

            }
        }
        return result;
    }

    /**
     * 加载页面layout
     */
    protected abstract View loadViewLayout(LayoutInflater inflater);

    protected abstract void findViewById(View view);

    protected abstract void processLogic();

    protected abstract void setListener();

    protected abstract void onBackPress();

    @Override
    protected void onResume() {
        LogUtil.info(BaseActivity.class, getClass() + " onResume ");
        if (gestureEnable) {
            handler.sendEmptyMessageDelayed(BaseHandler.TIME_TO_VAILD_GESTURE,
                BaseHandler.TIME_TO_VAILD_GESTURE_Delayed);
        }
        MobclickAgent.onPageStart(this.getClass().getName()); //统计页面
        MobclickAgent.onResume(this);
        mactivity = this;
        super.onResume();
    }

    @Override
    protected void onPause() {
        MobclickAgent.onPageEnd(this.getClass().getName());
        MobclickAgent.onPause(this);
        super.onPause();
    }

    public void popBackStack() {
        finish();
    }

    /**
     * 获取清空后的请求参数集合
     * @return
     */
    public HashMap<String, String> getParm() {
        if (parms == null) {
            parms = new HashMap<String, String>();
        }
        return parms;
    }

    public boolean isLogin() {
        if (!TextUtils.isEmpty(getToken())) {
            return true;
        }
        return false;
    }

    /**
     * 是否需要验证手势
     * @return
     */
    public boolean needValidGesture() {
        return isLogin() && !application.vaildGesturePwd
               && application.otherService.gestureIsOpened();
    }

    /**
     * 检查token是否过期
     * @return
     */
    public void checkToken() {
        if (!application.isNeed()) {

            if (!NetWorkUtil.isNetworkConnected(mContext)) {
                Intent intent = new Intent(BaseActivity.this, LockActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.slide_in_from_bottom, R.anim.silent_anim);
                return;
            }

            parms = getParm();
            parms.clear();
            parms.put("token", getToken());
            getDate(parms, Constants.USERINFOQUERY, handler, BaseHandler.CHECKTOKENSUC,
                BaseHandler.CHECKTOKENFAI, false, false, false);
            application.setNeed(true);
        }
    }

    /**
     * 点击事件
     */
    public abstract void onClick(View view);

    /**
     * 获取token
     * @return
     */

    public String getToken() {
        return application.getUser().token;
    }

    public boolean hasOpenThirdAct() {
        return application.getUser().hasOpenThirdAct;
    }

    public boolean hasBindPhone() {
        return application.getUser().hasBindPhone;
    }

    /**
     * 判断用户是否可投新手项目
     * true表示是可投或者未登录，false为不可投
     * @return
     */
    public boolean isNewMan() {
        if (!StringUtils.isEmpty((application.getUser().newerProject))) {
            if ("1".equals(application.getUser().newerProject)) {
                return true;
            } else {
                return false;
            }
        }
        return true;
    }

    /**
     * 判断用户是否可投万元体验金项目
     * true表示是可投或者未登录，false为不可投
     * @return
     */
    public boolean isNewManForWYTYJ() {
        if (!StringUtils.isEmpty((application.getUser().wytyjProject))) {
            if ("1".equals(application.getUser().wytyjProject)) {
                return true;
            } else {
                return false;
            }
        }
        return true;
    }

    /**
     * 获取快捷充值卡
     * @return
     */
    public BanklistItem getQuickBank() {
        return application.getQuickBank();
    }

    public void startNewActivity(Intent intent, int enterAnim, int exitAnim, boolean isFinish) {
        startActivity(intent);
        overridePendingTransition(enterAnim, exitAnim);
        if (isFinish) {
            finish();
        }
    }

    public void startNewActivityforresult(Intent intent, int enterAnim, int exitAnim,
                                          int requestCode) {
        startActivityForResult(intent, requestCode);
        overridePendingTransition(enterAnim, exitAnim);
    }

    /**
     * 弹出Toast
     *
     * @param text
     */
    public void showToast(String text) {
        PromptManager.showCustomToast(mContext, text);
    }

    /**
     * get请求 
     * 
     * @param params
     * @param path
     * @param handler
     * @param TUREMESSAGER
     * @param ERRORMESSAGER
     * @param isshow
     * @param showNonet
     * @param iscache
     */
    public void getDate(HashMap<String, String> params, String path, final Handler handler,
                        final int TUREMESSAGER, final int ERRORMESSAGER, final boolean isshow,
                        boolean showNonet, boolean iscache) {
        getDate(params, path, handler, TUREMESSAGER, ERRORMESSAGER, isshow, showNonet, iscache,
            "3.0");
    }

    /**
     * get请求  （for3.0 版本）
     * 
     * @param params
     * @param path
     * @param handler
     * @param TUREMESSAGER
     * @param ERRORMESSAGER
     * @param isshow
     * @param showNonet
     * @param iscache
     */
    public void getDate(HashMap<String, String> params, String path, final Handler handler,
                        final int TUREMESSAGER, final int ERRORMESSAGER, final boolean isshow,
                        boolean showNonet, boolean iscache, String version) {
        if (!NetWorkUtil.isNetworkConnected(mContext)) {
            showToast("网络不可用，请检查您的网络连接");
            return;
        }
        params.put("version", version);
        String randomNumber = RandomUtils.getRandomNumbersAndLetters(32);
        String sign = Signature.getSign(params, Constants.Appkey, randomNumber);
        params.put("nonceStr", randomNumber);
        params.put("sign", sign);
        LogUtil.info(BaseActivity.class, path + "?" + params.toString());
        HttpUtil.doGet(mContext, path, params, new RequestCallBack<String>() {
            private Dialog loading_dialog;

            @Override
            public void onStart() {
                if (isshow) {
                    loading_dialog = PromptManager.showLoadDataDialog(mactivity, "正在加载...");
                }
                super.onStart();
            }

            @Override
            public void onSuccess(ResponseInfo<String> result) {

                if (!checkSign(result)) {
                    showToast("验签不通过，请求数据可能被篡改");
                    PromptManager.closeLoadDataDialog(loading_dialog);
                    return;
                } else {
                    PromptManager.closeLoadDataDialog(loading_dialog);
                    LogUtil.info("请求成功" + result.result);

                    Basebean r = JSON.parseObject(result.result, Basebean.class);
                    //服务器错误
                    if (Constants.REQUEST_CODE_SYSTEM_ERROR.equals(r.code)) {
                        handler.sendEmptyMessage(BaseHandler.SYSTEM_ERROR);
                        return;
                    }
                    //系统维护中
                    if (Constants.REQUEST_CODE_SYSTEM_UPGRADE.equals(r.code)) {
                        handler.sendEmptyMessage(BaseHandler.SYSTEM_UPGRADE);
                        return;
                    }
                    //token过期
                    if (Constants.REQUEST_TOKEN_TIMEOUT.equals(r.code)) {
                        handler.sendEmptyMessage(BaseHandler.TOKEN_TIME_OUT);
                        return;
                    }
                    //token无效
                    if (Constants.REQUEST_CODE_TOKEN_INVALID.equals(r.code)) {
                        handler.sendEmptyMessage(BaseHandler.TOKEN_INVALID);
                        return;
                    }

                    //请求码是否为验证token是否失效
                    if (BaseHandler.CHECKTOKENSUC == TUREMESSAGER) {
                        Intent intent = new Intent(BaseActivity.this, LockActivity.class);
                        startActivity(intent);
                        overridePendingTransition(R.anim.slide_in_from_bottom, R.anim.silent_anim);
                    } else {
                        Message message = Message.obtain();
                        message.what = TUREMESSAGER;
                        message.obj = result.result;
                        handler.sendMessage(message);
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String result) {
                PromptManager.closeLoadDataDialog(loading_dialog);

                if (BaseHandler.CHECKTOKENFAI == ERRORMESSAGER) {
                    Intent intent = new Intent(BaseActivity.this, LockActivity.class);
                    startActivity(intent);
                    overridePendingTransition(R.anim.slide_in_from_bottom, R.anim.silent_anim);
                } else {
                    LogUtil.info("请求失败：" + result);
                    Message message = Message.obtain();
                    message.what = ERRORMESSAGER;
                    message.obj = result;
                    handler.sendMessage(message);
                }
            }
        });

    }

    /**
     * 从接口获取常量数据
     * 
     * @param isshow
     */
    public void getConstantData(final boolean isshow) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                if (!NetWorkUtil.isNetworkConnected(mContext)) {
                    showToast("网络不可用，请检查您的网络连接");
                    return;
                }
                HashMap<String, String> params = new HashMap<String, String>();
                params.put("dataToken", getLoacalDataToken());
                params.put("version", "3.0");
                String randomNumber = RandomUtils.getRandomNumbersAndLetters(32);
                String sign = Signature.getSign(params, Constants.Appkey, randomNumber);
                params.put("nonceStr", randomNumber);
                params.put("sign", sign);
                HttpUtil.doGet(mContext, Constants.CONSTANTQUERY, params,
                    new RequestCallBack<String>() {
                        private Dialog loading_dialog;

                        @Override
                        public void onStart() {
                            if (isshow) {
                                loading_dialog = PromptManager.showLoadDataDialog(mactivity,
                                    "正在获取常量数据...");
                            }
                            super.onStart();
                        }

                        @Override
                        public void onSuccess(ResponseInfo<String> result) {
                            if (!checkSign(result)) {
                                showToast("常量数据获取失败，请求数据可能被篡改");
                                PromptManager.closeLoadDataDialog(loading_dialog);
                                return;
                            } else {
                                PromptManager.closeLoadDataDialog(loading_dialog);
                                Basebean constantData = JSON.parseObject(result.result,
                                    Basebean.class);
                                if (constantData.isOk()) {
                                    ConstantData mConstantData = JSON.parseObject(
                                        constantData.data, ConstantData.class);
                                    //比较本地datatoken与请求datatoken不相同 并且 list不为空，则更新保存数据
                                    if (!(getLoacalDataToken().equals(mConstantData.getDataToken()))
                                        && !StringUtils.isEmpty(mConstantData.getList())) {

                                        List<ConstantDataUnit> mDataList = JSON.parseArray(
                                            mConstantData.getList(), ConstantDataUnit.class);
                                        List<ConstantDataUnit> localDataList = getLocalDataList();
                                        List<ConstantDataUnit> newList = getDifferentFromTwoList(
                                            mDataList, localDataList);

                                        changeListToMap(newList);
                                        ConstantData newConstantData = new ConstantData();
                                        newConstantData.setList(JSON.toJSONString(newList));
                                        newConstantData.setDataToken(mConstantData.getDataToken());
                                        String newConstantDataStr = JSON
                                            .toJSONString(newConstantData);
                                        PreferencesUtils.putString(mContext, CONSTANTDATA,
                                            newConstantDataStr);
                                    }
                                }
                            }
                        }

                        @Override
                        public void onFailure(HttpException e, String result) {
                            PromptManager.closeLoadDataDialog(loading_dialog);

                        }
                    });
            }
        }).start();
    }

    /**
     * 比较两个的差异list 并生成新的list (基于网络请求获得的list)
     * 
     * @param newList
     * @param oldList
     */
    protected List<ConstantDataUnit> getDifferentFromTwoList(List<ConstantDataUnit> newList,
                                                             List<ConstantDataUnit> oldList) {
        if (ListUtils.isEmpty(oldList)) {
            return newList;
        }
        List<ConstantDataUnit> result = new ArrayList<ConstantDataUnit>();
        for (int i = 0; i < newList.size(); i++) {
            boolean isCommon = false;
            for (int j = 0; j < oldList.size(); j++) {
                if (oldList.get(j).getKey().equals(newList.get(i).getKey())) {
                    if (Integer.parseInt(newList.get(i).getVer()) > Integer.parseInt(oldList.get(j)
                        .getVer())) {
                        result.add(newList.get(i));
                    } else {
                        result.add(oldList.get(j));
                    }
                    isCommon = true;
                }
            }
            if (!isCommon) {
                result.add(newList.get(i));
            }
        }
        return result;
    }

    /**
     * 获取本地存储的常量list数据
     * 
     * @return
     */
    private List<ConstantDataUnit> getLocalDataList() {
        List<ConstantDataUnit> mList = null;
        String constantDataStr = PreferencesUtils.getString(mContext, CONSTANTDATA);
        if (!StringUtils.isEmpty(constantDataStr)) {
            ConstantData constantData = JSON.parseObject(constantDataStr, ConstantData.class);
            mList = JSON.parseArray(constantData.getList(), ConstantDataUnit.class);
        }
        return mList;
    }

    /**
     * 获取本地datatoken数据
     * 
     * @return
     */
    private String getLoacalDataToken() {
        String dataToken = "";
        String constantDataStr = PreferencesUtils.getString(mContext, CONSTANTDATA);
        if (!StringUtils.isEmpty(constantDataStr)) {
            ConstantData constantData = JSON.parseObject(constantDataStr, ConstantData.class);
            dataToken = constantData.getDataToken();
        }
        return dataToken;
    }

    /**
     * 将list数据转为map, 并将map存储到内存
     * 
     * @return
     */
    private Map<String, ConstantDataUnit> changeListToMap(List<ConstantDataUnit> sourceList) {
        Map<String, ConstantDataUnit> map = new HashMap<String, ConstantDataUnit>();
        if (ListUtils.isEmpty(sourceList)) {
            return null;
        }
        for (int i = 0; i < sourceList.size(); i++) {
            map.put(sourceList.get(i).getKey(), sourceList.get(i));
        }
        application.setConstantDataMap(map);
        return map;
    }

    /**
     * 通过key获得常量数据（内存或者本地）
     * 如果没哟数据则请求
     * 
     * @param key
     * @return
     */
    public ConstantDataUnit getConstantDataByKey(String key) {
        Map<String, ConstantDataUnit> constantDataMap = application.getConstantDataMap();
        if (constantDataMap == null) {
            constantDataMap = changeListToMap(getLocalDataList());
        }
        if (constantDataMap == null || constantDataMap.get(key) == null) {
            //说明内存和本地都没有，或者数据中没有对应的key  需要从新加载
            getConstantData(true);
            return null;
        }
        ConstantDataUnit mData = constantDataMap.get(key);
        return mData;
    }

    /*
     * 获取数据 post请求
     */
    public void postDate(HashMap<String, String> params, String path, final Handler handler,
                         final int TUREMESSAGER, final int ERRORMESSAGER, final boolean isshow,
                         boolean showNonet, boolean iscache) {
        postDate(params, path, handler, TUREMESSAGER, ERRORMESSAGER, isshow, showNonet, iscache,
            "3.0");
    }

    /*
     * 获取数据 post请求
     */
    public void postDate(HashMap<String, String> params, String path, final Handler handler,
                         final int TUREMESSAGER, final int ERRORMESSAGER, final boolean isshow,
                         boolean showNonet, boolean iscache, String version) {
        if (!NetWorkUtil.isNetworkConnected(mContext)) {
            showToast("网络不可用，请检查您的网络连接");
            return;
        }

        params.put("version", version);
        String randomNumber = RandomUtils.getRandomNumbersAndLetters(32);
        params.put("nonceStr", randomNumber);
        String sign = Signature.getSign(params, Constants.Appkey, randomNumber);
        params.put("sign", sign);
        LogUtil.info(BaseActivity.class, path + "?" + params.toString());

        HttpUtil.doPost(mContext, path, params, new RequestCallBack<String>() {

            private Dialog loading_dialog;

            @Override
            public void onStart() {
                if (isshow) {
                    loading_dialog = PromptManager.showLoadDataDialog(mactivity, "正在加载...");
                }
                super.onStart();
            }

            @Override
            public void onSuccess(ResponseInfo<String> result) {

                if (!checkSign(result)) {
                    showToast("验签不通过，请求数据可能被篡改");
                    PromptManager.closeLoadDataDialog(loading_dialog);
                    return;
                } else {
                    PromptManager.closeLoadDataDialog(loading_dialog);
                    LogUtil.info("请求成功" + result.result);

                    Basebean r = JSON.parseObject(result.result, Basebean.class);
                    //服务器错误
                    if (Constants.REQUEST_CODE_SYSTEM_ERROR.equals(r.code)) {
                        handler.sendEmptyMessage(BaseHandler.SYSTEM_ERROR);
                        return;
                    }
                    //系统维护中
                    if (Constants.REQUEST_CODE_SYSTEM_UPGRADE.equals(r.code)) {
                        handler.sendEmptyMessage(BaseHandler.SYSTEM_UPGRADE);
                        return;
                    }
                    //token过期
                    if (Constants.REQUEST_TOKEN_TIMEOUT.equals(r.code)) {
                        handler.sendEmptyMessage(BaseHandler.TOKEN_TIME_OUT);
                        return;
                    }
                    //token无效
                    if (Constants.REQUEST_CODE_TOKEN_INVALID.equals(r.code)) {
                        handler.sendEmptyMessage(BaseHandler.TOKEN_INVALID);
                        return;
                    }

                    if (BaseHandler.CHECKTOKENSUC == TUREMESSAGER) {
                        Intent intent = new Intent(BaseActivity.this, LockActivity.class);
                        startActivity(intent);
                        overridePendingTransition(R.anim.slide_in_from_bottom, R.anim.silent_anim);
                    } else {
                        Message message = Message.obtain();
                        message.what = TUREMESSAGER;
                        message.obj = result.result;
                        handler.sendMessage(message);
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String result) {
                PromptManager.closeLoadDataDialog(loading_dialog);

                if (BaseHandler.CHECKTOKENFAI == ERRORMESSAGER) {
                    Intent intent = new Intent(BaseActivity.this, LockActivity.class);
                    startActivity(intent);
                    overridePendingTransition(R.anim.slide_in_from_bottom, R.anim.silent_anim);
                } else {
                    LogUtil.info("请求失败：" + result);
                    Message message = Message.obtain();
                    message.what = ERRORMESSAGER;
                    message.obj = result;
                    handler.sendMessage(message);
                }
            }
        });
    }

    private synchronized boolean checkSign(ResponseInfo<String> result) {
        HashMap<String, String> map = new HashMap<String, String>();
        Basebean r = JSON.parseObject(result.result, Basebean.class);
        if (TextUtils.isEmpty(r.sign) || TextUtils.isEmpty(r.nonceStr)) {
            LogUtil.info("API返回的数据签名数据不存在，有可能被第三方篡改!!!");
            return false;
        }
        map.put("codeDesc", r.codeDesc);
        map.put("nonceStr", r.nonceStr);
        map.put("code", r.code);
        if (r.data != null) {
            map.put("data", r.data);
        }
        String sign = Signature.getSign(map, Constants.Appkey);
        if (!sign.equals(r.sign)) {
            //签名验不过，表示这个API返回的数据有可能已经被篡改了
            LogUtil.info("API返回的数据签名验证不通过，有可能被第三方篡改!!!");
            return false;
        }
        LogUtil.info("恭喜，API返回的数据签名验证通过!!!");
        return true;

    }

    public Context getContext() {
        return mContext;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            LogUtil.info(BaseActivity.class, "keyEvent " + keyCode);
            onBackPress();
        }
        //        return super.onKeyDown(keyCode, event);
        return true; //保证浏览器内部的返回跳转
    }

    @Override
    protected void onDestroy() {
        LogUtil.info(BaseActivity.class, " onDestory " + getClass().getName());
        super.onDestroy();
        PromptManager.closeLoadDataDialog();
        TwoTigerApp.getInstance().removeActivity(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        PromptManager.closeLoadDataDialog();
    }

    /**
     * 退出App
     */
    public void exitApp() {
        MobclickAgent.onKillProcess(mContext);//用来保存统计数据(友盟统计)
        application.exit();
    }

    /**
     * 收起软键盘
     */
    public void hideSoftInputMethod(Context context, View v) {
        if (v != null) {
            InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

    /**显示输入法
     * @param 触发的view
     */
    public void visibleInputmethod(View v) {
        InputMethodManager imm = (InputMethodManager) getApplicationContext().getSystemService(
            Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(v, InputMethodManager.SHOW_FORCED);
    }

    long mExitTime = 0;

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (PackageUtils.isTopActivity(mactivity, "com.twotiger.and.activity.HomeActivity")) {
                if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
                    if ((System.currentTimeMillis() - mExitTime) > 2000) {
                        Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                        mExitTime = System.currentTimeMillis();
                    } else {
                        exitApp();
                    }
                }
                return true;
            }
            mExitTime = 0;
            return super.dispatchKeyEvent(event);
        }

        return super.dispatchKeyEvent(event);
    }
}
